package com.hzyl.famousreader.view.activity;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.*;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.ThemeColor;
import com.hzyl.famousreader.databinding.ActivityBookBinding;
import com.hzyl.famousreader.repository.persistence.entity.Book;
import com.hzyl.famousreader.router.Router;
import com.hzyl.famousreader.viewmodel.BookViewModel;

import java.util.Date;

@Route(path = "/book/info")
public class BookActivity extends BaseActivity {

  @Autowired
  Book book;

  private ActivityBookBinding binding;

  private BookViewModel bookViewModel;

  private boolean isAddToBookshelf = false;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ARouter.getInstance().inject(this);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_book);

    int colorValue = SPUtils.getInstance().getInt(Constant.SP_THEME_COLOR,  ThemeColor.DEFAULT.getColor());
    BarUtils.setStatusBarColor(this, colorValue, 0);
    binding.toolbar.setBackgroundColor(colorValue);

    bookViewModel = ViewModelProviders.of(this).get(BookViewModel.class);

    binding.setBook(book);

    //是否已添加到书架
    bookViewModel.isAddToBookshelf(book.getId()).observe(this, new Observer<Integer>() {
      @Override
      public void onChanged(@Nullable Integer integer) {
        if (integer != null && integer > 0) {
          isAddToBookshelf = false;
          binding.bookTvAddToBookshelf.setText("从书架移除");
        } else {
          isAddToBookshelf = true;
          binding.bookTvAddToBookshelf.setText("添加至书架");
        }
      }
    });

    //添加或移除书籍
    binding.bookAddToBookshelf.setOnClickListener(v -> {
      if (isAddToBookshelf) {
        book.setChapter(0);
        book.setPage(0);
        book.setLastReadDate(new Date());
        bookViewModel.addBookToBookshelf(book);
      } else {
        bookViewModel.deleteBook(book.getId());
      }
    });

    //阅读
    binding.bookRlRead.setOnClickListener(v -> {
      PermissionUtils.permission(Manifest.permission.WRITE_EXTERNAL_STORAGE).callback(new PermissionUtils.SimpleCallback() {
        @Override
        public void onGranted() {
          ARouter.getInstance()
            .build(Router.ACTIVITY_READ)
            .withObject("book", book)
            .withString("bookName", book.getName())
            .navigation();
        }

        @Override
        public void onDenied() {
          ToastUtils.showShort("没有写缓存的权限");
        }
      }).request();
    });
  }
}
